package com.lc.config;

import io.jsonwebtoken.Jwts;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

/**
 * Swagger2配置类
 */
@Component
@EnableSwagger2
public class Swagger2Config {

    @Bean
    public Docket getDocket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.lc.controller"))
                .paths(PathSelectors.any())
                .build()
                .securityContexts(securityContexts())
                .securitySchemes(securitySchemes());
    }

    /**
     * 安全上下文
     * @return
     */
    private List<SecurityContext> securityContexts() {
        List<SecurityContext> list = new ArrayList<>();
        //设置需要认证的路径
        list.add(getContextByPath("/hello/.*"));
        return list;
    }

    private SecurityContext getContextByPath(String path) {
        return SecurityContext.builder()
                .securityReferences(securityReferences())
                .forPaths(PathSelectors.regex(path))
                .build();
    }

    /**
     * 安全参考
     * @return
     */
    private List<SecurityReference> securityReferences() {
        List<SecurityReference> list = new ArrayList<>();
        AuthorizationScope authorizationScope = new AuthorizationScope("global","accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        list.add(new SecurityReference("Authorization",authorizationScopes));
        return list;
    }


    /**
     * 配置安全方案
     * @return
     */
    private List<ApiKey> securitySchemes() {
        //设置请求头
        List<ApiKey> res = new ArrayList<>();
        ApiKey apiKey = new ApiKey("Authorization","Authorization","Header");
        res.add(apiKey);
        return res;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("云e办后台接口文档")
                .version("1.0")
                .contact(new Contact("lc","lcbc6.gitee.io","1300474771@qq.com"))
                .description("详细文档")
                .build();
    }
}
